package cn.base.web.cahe.temporary;

import cn.base.web.cahe.TemporaryCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;

@Component
@Slf4j
@ConditionalOnProperty(name = "redis.enabled", havingValue = "true",matchIfMissing=true)
@Primary
public class RedisTemporaryCache implements TemporaryCache {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void set(String key, Object value, Duration timeout) {
        redisTemplate.opsForValue().set(key, value,timeout);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 取值同时更新过期时间
     * @param key
     * @param timeout
     * @return
     */
    @Override
    public Object getAndExpire(String key, Duration timeout) {
        return redisTemplate.opsForValue().getAndExpire(key,timeout);
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }


}
